package cn.tannn.util;


import cn.jdevelops.exception.exception.BusinessException;
import cn.tannn.entity.ClassInfo;
import cn.tannn.entity.FieldInfo;
import cn.tannn.entity.ParamInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.commons.lang3.StringUtils.indexOf;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 表格解析Util
 *
 * @author zhengkai.blog.csdn.net
 */
@Slf4j
public class TableParseUtil {


    /**
     * 解析DDL SQL生成类信息
     * @param tableSql sql
     * @param ignorePrefix 忽略的前缀字符
     * @return ClassInfo
     */
    public static ClassInfo ddlToBean(String tableSql,String ignorePrefix){
        /* ---------对sql进出预处理----------- */
        String pretreatmentSql = SqlUtil.sqlPretreatment(tableSql);

        /* ---------获取表名----------- */
        String tableName = SqlUtil.getTableName(pretreatmentSql);

        /* ---------获取类名----------- */
        String  className = SqlUtil.getClassName(tableName,ignorePrefix);

        /* ---------获取类注釋----------- */
        String  classComment = SqlUtil.getClassComment(pretreatmentSql);

        /* ---------获取字段信息----------- */
        List<FieldInfo> fieldList = SqlUtil.getFieldList(pretreatmentSql);

        /* ---------获取主键信息----------- */
        ClassInfo.PrimaryKey  columnKey =  SqlUtil.getColumnKey(pretreatmentSql);

        ClassInfo classInfo = new ClassInfo();
        classInfo.setTableName(tableName);
        classInfo.setClassName(className);
        classInfo.setClassComment(isNotBlank(classComment)?classComment:tableName);
        classInfo.setFieldList(fieldList);
        for (FieldInfo fieldInfo : fieldList){
            if(columnKey.getPk().equalsIgnoreCase(fieldInfo.getColumnName())){
                columnKey.setPkStrType(fieldInfo.getFieldClass());
                break;
            }
        }
        classInfo.setPrimaryKey(columnKey);
        return classInfo;
    }


}